package demo.servlet;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jgit.api.Git;

import demo.output.CodeMessage;
import demo.util.CodeMessageUtil;
import demo.util.GitUtil;

/**
 * Servlet implementation class CheckGitUserRepoServlet
 */
@WebServlet("/CheckGitUserRepoServlet")
public class CheckGitUserRepoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CheckGitUserRepoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		String url = request.getParameter("url");
		CodeMessage cm = new CodeMessage();
		if(url == null || "".equals(url.trim())) {
			cm.setCode(CodeMessageUtil.CD_400);
			cm.setMessage("git库url 为空.");
		} else {
//			url = url.trim();
//			if(url.endsWith("/")) {
//				url = url.substring(0, url.length() - 1);
//			}
//			if(!url.endsWith(".git")) {
//				url += ".git";
//			}
			url = GitUtil.wrapGitUrl(url);
//			File localPath = File..createTempFile("TestGitRepository", "");
//			String tmpdir = System.getProperty("java.io.tmpdir");
//			tmpdir += File.separator + random();
//			File localPath = new File(tmpdir);
//			localPath.mkdir();
			File localPath = new File(GitUtil.getTempFolder());
			System.out.println("TempFile:" + localPath.getAbsolutePath());
			try {
				Git result = Git.cloneRepository()
		                .setURI(url)
		                .setDirectory(localPath)
		                .call();
				System.out.println("GIT:" + result.getRepository().getDirectory());
				result.close();
				cm.setCode(CodeMessageUtil.CD_200);
				cm.setMessage("OK");
			} catch (Exception e) {
				cm.setCode(CodeMessageUtil.CD_502);
				cm.setMessage(e.getMessage());
			}
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		response.getWriter().print(cm.toJson());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
	
	

}
